package com.atguigu.jeccache.service.impl;

import com.atguigu.jeccache.entity.pojo.User;
import com.atguigu.jeccache.mapper.UserMapper;
import com.atguigu.jeccache.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;


/**
 * @author Jungle
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(long userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public String getToken(Integer type) {
        String s = generateOrderNo("O-");
        log.info("生成token==>{},type==>{},时间==>{}", s, type, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return s;
    }


    /**
     * 基于业务前缀+基于时间戳+随机数
     */
    public static String generateOrderNo(String prefix) {
        // 获取当前时间戳（毫秒级）
        long timestamp = System.currentTimeMillis();
        // 生成一个 4 位的随机数
        Random random = new Random();
        // 生成 [0, 9999] 之间的随机数
        int randomNum = random.nextInt(10000);
        // 拼接时间戳和随机数
        return prefix + timestamp + String.format("%04d", randomNum);
    }

}
